package utils;

import java.io.*;
import java.util.*;

/**
 * 删除文件中相同的行
 * */
public class RemoveFileSameRow {

    //读文件
    public static List<String> read(File file) {
        String string = "";
        InputStreamReader isr;
        try {
            isr = new InputStreamReader(new FileInputStream(file));
            BufferedReader br = new BufferedReader(isr);
            int i = 0;
            while (true) {
                i = br.read();
                if (i != -1)
                    string = string + String.valueOf((char) i);
                else break;
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Arrays.asList(string.split("\n|\r"));
    }

    //获取相同
    public static HashSet<String> sameSubString(List<String> s1, List<String> s2) {
        //保存相同的子串
        HashSet<String> result = new HashSet<String>();
        for (String s : s1)
            if (s2.contains(s))
                result.add(s);
        for (String s : s2)
            if (s1.contains(s))
                result.add(s);
        return result;
    }

    //去重
    public static List<String> removeSame(List<String> list, HashSet<String> sameSet) {
        List arrayList = new ArrayList(list);
        Iterator<String> iterator = arrayList.iterator();
        while (iterator.hasNext()) {
            String str = iterator.next();
            if (sameSet.contains(str)) {
                iterator.remove();
            }
        }
        return arrayList;
    }

    //写文件
    public static void writeFileContext(List<String> strings, String path) throws Exception {
        File file = new File(path);
        //如果没有文件就创建
        if (!file.isFile()) {
            file.createNewFile();
        }
        BufferedWriter writer = new BufferedWriter(new FileWriter(path));
        for (String l : strings) {
            writer.write(l + "\r\n");
        }
        writer.close();
    }
}
